package nio;

import io.netty.util.concurrent.DefaultThreadFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.*;

/**
 * @author songZiHao
 * @version 1.0.0
 * @ClassName NioClient.java
 * @Description TODO
 * @createTime 2020年04月29日 16:04:00
 */
public class NioClient {
	public static void main(String[] args) {
		try {
			SocketChannel socketChannel = SocketChannel.open();
			socketChannel.configureBlocking(false);
			Selector selector = Selector.open();
			socketChannel.register(selector, SelectionKey.OP_CONNECT);
			socketChannel.connect(new InetSocketAddress("127.0.0.1",8899));
			while (true){
				selector.select();
				Set<SelectionKey> keys = selector.selectedKeys();
				Iterator<SelectionKey> keyIterator = keys.iterator();
				if (keyIterator.hasNext()){
					SelectionKey selectionKey = keyIterator.next();
					SocketChannel client=(SocketChannel)selectionKey.channel();
					ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
					if (client.isConnectionPending()){
						client.finishConnect();
						byteBuffer.put((LocalDateTime.now()+"连接成功").getBytes());
						byteBuffer.flip();
						client.write(byteBuffer);
					}
					ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 6, 100, TimeUnit.SECONDS, new LinkedBlockingDeque<>(),new DefaultThreadFactory("123"));
					executor.submit(()->{
						while (true){
							try {
								byteBuffer.clear();
								InputStreamReader reader = new InputStreamReader(System.in);
								BufferedReader bufferedReader = new BufferedReader(reader);
								String readLine = bufferedReader.readLine();
								byteBuffer.put(readLine.getBytes());
								byteBuffer.flip();
								client.write(byteBuffer);
							}catch (Exception e){
								e.printStackTrace();
							}
						}
					});
					keyIterator.remove();
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}
}
